package com.birdboot.core;

import com.birdboot.http.EmptyRequestException;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 该线程任务负责与指定客户端进行HTTP交互
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            HttpServletResponse response = new HttpServletResponse(socket);

            //2处理请求
            DispatcherServlet.getInstance().service(request,response);

            //3发送响应
            response.response();//调用响应对象的发送方法,让其将表示的响应以标准响应格式发送给客户端

        } catch (IOException e) {
            e.printStackTrace();
        } catch (EmptyRequestException e) {
            //如果遇到空请求,则不做任何处理(达到忽略本次处理的目的)
        } finally {
            try {
                //HTTP协议要求与客户端交互完毕后要断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}






